import AsyncStorage from '@react-native-async-storage/async-storage';

type Value = Record<string, any>;

export class Storage {
  private namespace = '@@global';

  constructor(namespace?: string) {
    if (namespace) this.namespace = namespace;
  }

  private getKey = (key: string) => {
    return [this.namespace, key].join('.');
  }

  public clear = () => {
    return AsyncStorage.clear();
  }

  public setItem = (key: string, value: Value) => {
    key = this.getKey(key);
    const json = JSON.stringify(value);
    return AsyncStorage.setItem(key, json);
  }

  public getItem = async <T = any>(key: string) => {
    key = this.getKey(key);
    const result = await AsyncStorage.getItem(key);
    if (!result) return null;
    return JSON.parse(result) as T;
  }

  public removeItem = (key: string) => {
    key = this.getKey(key);
    return AsyncStorage.removeItem(key);
  }
}